package com.lyd.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器
 */

@ControllerAdvice(annotations = {RestController.class, Controller.class})
//Controller中加了RestController和Controller注解的类都会被进行异常处理
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {


    /**
     * 异常处理方法
     * @param exception
     * @return
     */
    ////SQLIntegrityConstraintViolationException异常信息类
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException exception){
        log.error(exception.getMessage());

        if (exception.getMessage().contains("Duplicate entry")){
            String[] spilt = exception.getMessage().split(" ");
            String msg = spilt[2]+"已存在";
            return R.error(msg);
        }

        return R.error("新增员工失败，未知错误");
    }



    /**
     * 异常处理方法
     * @param exception
     * @return
     */
    ////CustomException业务异常类
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException exception){
        log.error(exception.getMessage());

        return R.error(exception.getMessage());   //获取CategoryServiceImpl中抛出的错误message
    }
}
